package main

import (
	"fmt"
	"net/http"
	"log"
	"bytes"
	_ "encoding/json"
	"encoding/json"
	"reflect"
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"time"
)

func main() {

	timer1()
}

func seletcGet()  {
	resp, err := http.Get("http://api.help.bj.cn/apis/aqi3/?id=changzhi")
	if err != nil {
		// handle error
		log.Println(err)
		return
	}
	defer resp.Body.Close()
	headers := resp.Header

	for k, v := range headers {
		fmt.Printf("k=%v, v=%v\n", k, v)
	}

	fmt.Printf("resp status %s,statusCode %d\n", resp.Status, resp.StatusCode)

	fmt.Printf("resp Proto %s\n", resp.Proto)

	fmt.Printf("resp content length %d\n", resp.ContentLength)

	fmt.Printf("resp transfer encoding %v\n", resp.TransferEncoding)

	fmt.Printf("resp Uncompressed %t\n", resp.Uncompressed)

	fmt.Println(reflect.TypeOf(resp.Body)) // *http.gzipReader

	buf := bytes.NewBuffer(make([]byte, 0, 512))

	length, _ := buf.ReadFrom(resp.Body)

	fmt.Println(len(buf.Bytes()))
	fmt.Println(length)
	fmt.Println(string(buf.Bytes()))

	b := string(buf.Bytes())

	var dat map[string]string
	if err := json.Unmarshal([]byte(b), &dat); err == nil {
		fmt.Println(dat)
		fmt.Println(dat["city"])
	} else {
		fmt.Println(err)
	}

	var memp1 emep
	memp1.pm10 = dat["pm10"]
	memp1.update = dat["update"]
	memp1.level = dat["level"]
	memp1.pm25 = dat["pm25"]
	memp1.aqi = dat["aqi"]
	memp1.city = dat["city"]
	memp1.co = dat["co"]

	add(&memp1)
}



type emep struct {
	city   string
	level  string
	update string
	aqi    string
	pm25   string
	pm10   string
	co     string
}

func add(emep1 *emep) {
	//打开数据库
	//DSN数据源字符串：用户名:密码@协议(地址:端口)/数据库?参数=参数值
	db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test?charset=utf8")
	if err != nil {
		fmt.Println(err)
	}
	insert(db, emep1)
}

//添加操作
func insert(db *sql.DB, emep *emep) {

	stmt, err := db.Prepare("INSERT INTO emep(city, `level`,`update`,aqi,pm25,pm10,co) VALUES(?, ?,?, ?, ?, ?, ?)")
	defer stmt.Close()
	if err != nil {
		log.Println(err)
		return
	}
	stmt.Exec(emep.aqi, emep.city, emep.co, emep.level, emep.pm10, emep.update, emep.pm10)
	fmt.Print("************ 插入成功 ************")
}


func timer1() {
	timer1 := time.NewTicker(1 * time.Second)
	for {
		select {
		case <-timer1.C:

			seletcGet()
		}
	}
}